package com.baofu.paycore.service.validate.impl.recharge;

import com.baofu.paycore.common.enums.RedisKeyEnum;
import com.baofu.paycore.manager.cache.RedisLockManager;
import com.baofu.paycore.manager.model.PayBaseBO;
import com.baofu.paycore.manager.storer.OrderRepository;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.baofu.paycore.service.facade.model.PayBaseResDTO;
import com.baofu.paycore.service.facade.model.recharge.RechargeConfirmDTO;
import com.google.common.base.Objects;
import com.system.commons.result.Result;
import com.system.commons.utils.BeanCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 * </p>
 * User: Xiachen Date: 2017/4/6  Version: 1.0
 */
@Slf4j
@Component
public class RechargeConfirmValidate {
    /**
     * redis锁服务
     */
    @Autowired
    private RedisLockManager lockManager;


    /**
     * 锁定支付订单
     *
     * @param t     被校验对象
     */
    public boolean lock(RechargeConfirmDTO t){
        return lockManager.lock(RedisKeyEnum.PAY_SERVICE,t.getRequestBizNo(),t.getRequestOrderNo());
    }

    /**
     * 释放订单锁
     *
     * @param t     被校验对象
     */
    public void release(RechargeConfirmDTO t,boolean flag){
        if(flag){
            lockManager.release(RedisKeyEnum.PAY_SERVICE,t.getRequestBizNo(),t.getRequestOrderNo());
        }
    }

    /**
     * 订单状态校验
     *
     * @param t     被校验对象
     */
    public <E> Result<E> validateOrder(RechargeConfirmDTO t, OrderRepository orderRepository, Class<E> clazz) {
        PayBaseBO order = orderRepository.checkIdempotent(t.getRequestBizNo(), t.getRequestOrderNo(), t.getRequestSystem());
        if (order == null) {
            log.warn("订单不存在:{},{}", t.getRequestBizNo(), t.getRequestOrderNo());
            return new Result<>(BeanCopyUtil.objConvert(new PayBaseResDTO(PayCoreErrorCode.ORDER_IS_NOT_EXISTED.getErrorCode(),
                    PayCoreErrorCode.ORDER_IS_NOT_EXISTED.getErrorDesc(), PayStatusEnums.FAIL.getCode()), clazz));
        }

        if (Objects.equal(PayStatusEnums.SUCCESS.getCode(), order.getStatus())) {
            log.warn("原订单状态交易已经成功 {}", order.getStatus());
            return new Result<>(BeanCopyUtil.objConvert(order, clazz));
        }
        t.setPayNo(order.getPayNo());
        return null;
    }
}
